import os
import random
import subprocess

# Default values
W = 64
H = 64

OUT = "world.bin"
WALLS_COUNT_1 = 16
WALLS_COUNT_2 = 6
PATH = os.path.split(__file__)[0]+"/.."

if(not(os.path.isfile(f"{PATH}/{OUT}"))):
    os.system(f"{PATH}/build/mkworld {W} {H} {OUT}")

world_ed = subprocess.Popen(
        [f"{PATH}/build/worlded", OUT],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE
)
stdout, _ = world_ed.communicate(b"size get\n")
W, H = (stdout.decode("utf-8")).split(" ")
W = int(W)
H = int(H)

levelCopy = []
level = [ [ True if(random.randint(0, WALLS_COUNT_1) > WALLS_COUNT_2) else False for j in range(W)] for i in range(H)]
while(level != levelCopy):
    levelCopy = level.copy()
    for i in range(10):
        for y in range(H):
            for x in range(W):
                neighborsCount = 0
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if(i == 0 and j == 0): continue
                        ly = i+y
                        lx = j+x
                        if(lx<0): lx = W-1
                        if(ly<0): ly = H-1
                        if(lx>=W): lx = 0
                        if(ly>=H): ly = 0
                        if(level[ly][lx]):
                            neighborsCount += 1
                if(not(level[y][x]) and neighborsCount > 5):
                    level[y][x] = True
                elif(level[y][x] and neighborsCount < 4):
                    level[y][x] = False

command = ''
for y in range(H):
    for x in range(W):
        if(level[y][x]):
            command += f"wall {x} {y}\n"
command += "wq\n"

world_ed = subprocess.Popen(
        [f"{PATH}/build/worlded", OUT],
        stdin=subprocess.PIPE,
)
world_ed.communicate(bytes(command, encoding="utf-8"))
